﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Runtime.Remoting.Messaging;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Collections;
using System.Runtime.CompilerServices;

namespace AspNetCs.Common
{

    /// <summary>
    /// 缓存操作类
    /// 
    /// </summary>
    public class Caches
    {
        #region 私有成员定义
        private Cache ObjCache = HttpRuntime.Cache;
        private short TimeOut = 720;
        #endregion

        #region 成员属性暴露
        public object this[string index]
        {
            get { return GetCache(index); }
            set { SetCache(index, value); }
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="CacheKey">缓存关键字</param>
        /// <returns>缓存数据</returns>
        public object GetCache(string CacheKey)
        {
            return ObjCache[CacheKey];
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="CacheKey">缓存关键字</param>
        /// <param name="CacheData">缓存数据</param>
        public void SetCache(string CacheKey, object CacheData)
        {
          
            ObjCache.Insert(CacheKey, RuntimeHelpers.GetObjectValue(CacheData));
        }

        /// <summary>
        /// 设置缓存
        /// 
        /// </summary>
        /// <param name="CacheKey">缓存关键字</param>
        /// <param name="CacheData">缓存数据</param>
        /// <param name="TimeOuts">超时时间</param>
        public void SetCache(string CacheKey, object CacheData, int TimeOuts)
        {
            ObjCache.Insert(CacheKey, RuntimeHelpers.GetObjectValue(CacheData), null, DateTime.Now.AddMinutes((double)TimeOuts), TimeSpan.Zero);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="CacheKey">缓存关键字</param>
        /// <param name="CacheData">缓存数据</param>
        /// <param name="Files">缓存依赖文件</param>
        public void SetCache(string CacheKey, object CacheData, string Files)
        {
            CacheDependency CacheDep = new CacheDependency(Files, DateTime.Now);
            SetCache(CacheKey, RuntimeHelpers.GetObjectValue(CacheData), TimeOut, CacheDep, CacheItemPriority.High);
        }

        /// <summary>
        /// 设置缓存
        /// 
        /// </summary>
        /// <param name="CacheKey">缓存关键字</param>
        /// <param name="CacheData">缓存数据</param>
        /// <param name="Priority">缓存级别</param>
        public void SetCache(string CacheKey, object CacheData, CacheItemPriority Priority)
        {
            SetCache(CacheKey, RuntimeHelpers.GetObjectValue(CacheData), TimeOut, null, Priority);
        }

        /// <summary>
        /// 设置缓存
        /// 
        /// </summary>
        /// <param name="CacheKey">缓存关键字</param>
        /// <param name="CacheData">缓存数据</param>
        /// <param name="TimeOuts">超时时间</param>
        /// <param name="CacheDep">依赖文件</param>
        /// <param name="Priority">缓存级别</param>
        public void SetCache(string CacheKey, object CacheData, int TimeOuts, CacheDependency CacheDep, CacheItemPriority Priority)
        {
            ObjCache.Insert(CacheKey, RuntimeHelpers.GetObjectValue(CacheData), CacheDep, DateTime.MaxValue, TimeSpan.FromHours((double)TimeOuts), Priority, null);
        }

        /// <summary>
        /// 清空缓存
        /// 
        /// </summary>
        public void ClearCache()
        {
            IDictionaryEnumerator CacheEnum = ObjCache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                ObjCache.Remove(CacheEnum.Key.ToString());
            }
        }
        #endregion
    }


    /*
     调用
     * 
            WebCache Cache1 = new WebCache();
            Cache1.CacheItemName = "Oneone";
            Cache1.CacheName = "keys";
            Cache1.ExpireTime = 1;
            Cache1.SetCache((object)new DataSet());

     */

    /// <summary>
    /// WebCache 的摘要说明
    /// </summary>
    public class WebCache
    {
        HttpResponse Response = HttpContext.Current.Response;

        /// <summary>
        /// 缓存名称
        /// </summary>
        protected string strCacheName = "";//缓存名称

        /// <summary>
        /// 缓存项目名称
        /// </summary>
        protected string strCacheItemName = "";//缓存项目名称

        /// <summary>
        /// 缓存过期时间,单位秒钟。
        /// </summary>
        protected int intExpireTime = 0;//缓存过期时间,单位秒钟

        /// <summary>
        /// 缓存类的版本。
        /// </summary>
        protected string strVersion = "";//缓存类的版本

        /// <summary>
        /// 缓存对象。
        /// </summary>
        protected Object objCacheObject = new object();//缓存对象


        /// <summary>
        /// 缓存键名称。
        /// </summary>
        protected string strCacheKey = "";//缓存键名称

        /// <summary>
        /// 缓存最后更新时间。
        /// </summary>
        protected string strLastUpdate = "";//缓存最后更新时间

        /// <summary>
        /// 操作结果。
        /// </summary>
        protected string strResult = "";//操作结果




        public WebCache()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //

            strCacheKey = strCacheItemName + "_" + strCacheName;
            strVersion = "VerSion 1.0";

        }

        #region 获得缓存类版本
        /// <summary>
        /// 获得缓存类版本。
        /// </summary>
        public string Version
        {
            get
            {
                return strVersion;
            }
        }
        #endregion


        #region 设置/获得缓存项目
        /// <summary>
        /// 设置/获得缓存项目。
        /// </summary>
        public string CacheItemName
        {
            get
            {
                return strCacheItemName;
            }
            set
            {
                strCacheItemName = value;
                strCacheKey = strCacheItemName + "_" + strCacheName;
            }
        }
        #endregion

        #region 设置/获得缓存名称
        /// <summary>
        /// 设置/获得缓存名称。
        /// </summary>
        public string CacheName
        {
            get
            {
                return strCacheName;
            }
            set
            {
                strCacheName = value;
                strCacheKey = strCacheItemName + "_" + strCacheName;
            }
        }
        #endregion

        #region 设置缓存过期时间间隔
        /// <summary>
        /// 设置缓存过期时间间隔。
        /// </summary>
        public int ExpireTime
        {
            get
            {
                return intExpireTime;
            }
            set
            {
                intExpireTime = value;
            }
        }
        #endregion

        #region 获得缓存最后更新时间
        /// <summary>
        /// 获得缓存最后更新时间。
        /// </summary>
        public string getLastUpDatetime
        {
            get
            {
                if (System.Web.HttpContext.Current.Cache[strCacheKey + "_UpDateTime"] != null)
                {
                    return System.Web.HttpContext.Current.Cache[strCacheKey + "_UpDateTime"].ToString();
                }
                else
                {
                    return "";
                }
            }
        }
        #endregion

        #region 获得缓存过期时间
        /// <summary>
        /// 读取缓存过期时间。
        /// </summary>
        public string getLostTime
        {
            get
            {
                if (System.Web.HttpContext.Current.Cache[strCacheKey + "_LostDateTime"] != null)
                {
                    return System.Web.HttpContext.Current.Cache[strCacheKey + "_LostDateTime"].ToString();
                }
                else
                {
                    return "";
                }
            }
        }
        #endregion

        #region 保存对象到缓存中
        public void SetCache(object objContent)
        {
            if (CheckParameter() == false) return;
            lock (objContent)
            {
                DateTime Dt = DateTime.Now;
                System.Web.HttpContext.Current.Cache.Insert(strCacheKey, objContent, null, Dt.AddSeconds(intExpireTime), System.TimeSpan.Zero);
                System.Web.HttpContext.Current.Cache.Insert(strCacheKey + "_UpDateTime", Dt.ToString(), null, Dt.AddSeconds(intExpireTime), System.TimeSpan.Zero);
                System.Web.HttpContext.Current.Cache.Insert(strCacheKey + "_LostDateTime", Dt.AddSeconds(intExpireTime), null, Dt.AddSeconds(intExpireTime), System.TimeSpan.Zero);
            }

        }


        #endregion


        #region 从缓存中取出对象
        /// <summary>
        /// 从缓存中取出对象。
        /// </summary>
        public object GetCache()
        {
            if (CheckParameter() == false) return null;
            lock (objCacheObject)
            {
                if (System.Web.HttpContext.Current.Cache[strCacheKey] != null)
                {
                    return System.Web.HttpContext.Current.Cache[strCacheKey];
                }
                else
                {
                    return null;
                }
            }
        }
        #endregion


        #region 从缓存中清空对象
        /// <summary>
        /// 从缓存中清空对象。
        /// </summary>
        public void Clear()
        {
            if (CheckParameter() == false) return;
            lock (objCacheObject)
            {
                if (System.Web.HttpContext.Current.Cache[strCacheKey] != null)
                {
                    System.Web.HttpContext.Current.Cache.Remove(strCacheKey);
                }
                if (System.Web.HttpContext.Current.Cache[strCacheKey + "_UpDateTime"] != null)
                {
                    System.Web.HttpContext.Current.Cache.Remove(strCacheKey + "_UpDateTime");
                }
                if (System.Web.HttpContext.Current.Cache[strCacheKey + "_LostDateTime"] != null)
                {
                    System.Web.HttpContext.Current.Cache.Remove(strCacheKey + "_LostDateTime");
                }
            }
        }
        #endregion


        #region 缓存对象是否有效
        /// <summary>
        /// 缓存对象是否有效。
        /// </summary>
        public bool ValidCache()
        {
            if (CheckParameter() == false) return false;
            lock (objCacheObject)
            {
                if (System.Web.HttpContext.Current.Cache[strCacheKey] == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        #endregion



        #region 获得缓存操作结果
        /// <summary>
        /// 获得缓存操作结果。
        /// </summary>
        public string getResult
        {
            get
            {
                return strResult;
            }
        }
        #endregion





        #region 检查缓存参数
        /// <summary>
        /// 检查缓存参数。
        /// </summary>
        public bool CheckParameter()
        {
            if (strCacheItemName == "")
            {
                strResult = "缓存项目名称为空";
                return false;
            }
            if (strCacheName == "")
            {
                strResult = "缓存名称为空";
                return false;
            }
            return true;
        }
        #endregion







        /// <summary>
        ///清除所有缓存
        /// </summary>
        public void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            ArrayList al = new ArrayList();
            while (CacheEnum.MoveNext())
            {
                al.Add(CacheEnum.Key);
            }
            foreach (string key in al)
            {
                _cache.Remove(key);
            }
        }

        /// <summary>
        /// 显示所有缓存
        /// </summary>
        public void show()
        {
            string str = "";
            IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();

            while (CacheEnum.MoveNext())
            {
                str += "缓存名<b>[" + CacheEnum.Key + "]</b><br />";
                str += "缓存值<b>[" + CacheEnum.Value + "]</b><br />";
            }
            Response.Write("当前网站总缓存数:" + HttpRuntime.Cache.Count + "<br />" + str);
        }

    }



}


